#include "addmemberpage.h"
#include <QDebug>
#include <QRegularExpression>

AddMemberPage::AddMemberPage(Database *db, QWidget *parent)
    : QWidget(parent), m_db(db)
{
    // 初始化服务层
    m_memberService = new MemberService(db);
    
    // 初始化UI组件指针
    m_mainLayout = nullptr;
    m_inputGroup = nullptr;
    m_inputLayout = nullptr;
    m_nameLabel = nullptr;
    m_nameEdit = nullptr;
    m_phoneLabel = nullptr;
    m_phoneEdit = nullptr;
    m_tipLabel = nullptr;
    m_buttonArea = nullptr;
    m_buttonLayout = nullptr;
    m_submitBtn = nullptr;
    m_clearBtn = nullptr;
    m_phoneValidator = nullptr;

    initUI();
    applyGreenThemeStyles();
}

AddMemberPage::~AddMemberPage()
{
    delete m_memberService;
    delete m_phoneValidator;
}

void AddMemberPage::initUI()
{
    // 主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(50, 50, 50, 50);
    m_mainLayout->setSpacing(30);

    // 设置输入表单区域
    setupInputForm();
    
    // 设置按钮区域
    setupButtonArea();
    
    // 添加弹性空间，使表单居中显示
    m_mainLayout->addStretch();
}

void AddMemberPage::setupInputForm()
{
    // 输入表单组
    m_inputGroup = new QGroupBox("新会员信息");
    m_inputGroup->setFixedSize(400, 250);
    m_mainLayout->addWidget(m_inputGroup, 0, Qt::AlignCenter);

    m_inputLayout = new QGridLayout(m_inputGroup);
    m_inputLayout->setContentsMargins(30, 40, 30, 30);
    m_inputLayout->setSpacing(20);

    // 会员姓名输入
    m_nameLabel = new QLabel("会员姓名:");
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText("请输入会员真实姓名");
    m_nameEdit->setMaxLength(50);
    
    m_inputLayout->addWidget(m_nameLabel, 0, 0);
    m_inputLayout->addWidget(m_nameEdit, 0, 1);

    // 手机号输入
    m_phoneLabel = new QLabel("手机号码:");
    m_phoneEdit = new QLineEdit();
    m_phoneEdit->setPlaceholderText("请输入11位手机号码");
    m_phoneEdit->setMaxLength(11);
    
    // 设置手机号验证器
    m_phoneValidator = new QRegularExpressionValidator(
        QRegularExpression("^1[3-9]\\d{9}$"), this);
    m_phoneEdit->setValidator(m_phoneValidator);
    
    m_inputLayout->addWidget(m_phoneLabel, 1, 0);
    m_inputLayout->addWidget(m_phoneEdit, 1, 1);

    // 提示信息
    m_tipLabel = new QLabel("提示：新会员初始余额为0元，等级为非会员");
    m_tipLabel->setWordWrap(true);
    m_inputLayout->addWidget(m_tipLabel, 2, 0, 1, 2);

    // 连接信号槽
    connect(m_nameEdit, &QLineEdit::textChanged, this, &AddMemberPage::onNameTextChanged);
    connect(m_phoneEdit, &QLineEdit::textChanged, this, &AddMemberPage::onPhoneTextChanged);
}

void AddMemberPage::setupButtonArea()
{
    // 按钮区域
    m_buttonArea = new QWidget();
    m_buttonArea->setFixedHeight(60);
    m_mainLayout->addWidget(m_buttonArea, 0, Qt::AlignCenter);

    m_buttonLayout = new QHBoxLayout(m_buttonArea);
    m_buttonLayout->setContentsMargins(0, 0, 0, 0);
    m_buttonLayout->setSpacing(20);

    // 提交按钮
    m_submitBtn = new QPushButton("添加会员");
    m_submitBtn->setFixedSize(100, 40);
    m_submitBtn->setEnabled(false); // 初始状态禁用
    
    // 清空按钮
    m_clearBtn = new QPushButton("清空重填");
    m_clearBtn->setFixedSize(100, 40);

    m_buttonLayout->addWidget(m_submitBtn);
    m_buttonLayout->addWidget(m_clearBtn);

    // 连接信号槽
    connect(m_submitBtn, &QPushButton::clicked, this, &AddMemberPage::onSubmitClicked);
    connect(m_clearBtn, &QPushButton::clicked, this, &AddMemberPage::onClearClicked);
}

void AddMemberPage::applyGreenThemeStyles()
{
    // 主窗口样式
    this->setStyleSheet(
        "QWidget { "
        "    background-color: #F0F8F0; "
        "    font-family: 'Microsoft YaHei'; "
        "    font-size: 16px; "
        "}"
    );

    // 分组框样式
    m_inputGroup->setStyleSheet(
        "QGroupBox { "
        "    font-size: 18px; "
        "    font-weight: bold; "
        "    color: #2E7D32; "
        "    border: 2px solid #4CAF50; "
        "    border-radius: 8px; "
        "    margin-top: 10px; "
        "    background-color: #FFFFFF; "
        "} "
        "QGroupBox::title { "
        "    subcontrol-origin: margin; "
        "    left: 15px; "
        "    padding: 0 8px 0 8px; "
        "    background-color: #FFFFFF; "
        "}"
    );

    // 标签样式
    QString labelStyle = 
        "QLabel { "
        "    color: #2E7D32; "
        "    font-size: 16px; "
        "    font-weight: bold; "
        "}";
    m_nameLabel->setStyleSheet(labelStyle);
    m_phoneLabel->setStyleSheet(labelStyle);
    
    // 提示标签样式
    m_tipLabel->setStyleSheet(
        "QLabel { "
        "    color: #666666; "
        "    font-size: 14px; "
        "    font-style: italic; "
        "    background-color: #E8F5E8; "
        "    padding: 8px; "
        "    border-radius: 4px; "
        "}"
    );

    // 输入框样式
    QString editStyle = 
        "QLineEdit { "
        "    border: 2px solid #CCCCCC; "
        "    border-radius: 6px; "
        "    padding: 8px; "
        "    font-size: 16px; "
        "    background-color: #FFFFFF; "
        "} "
        "QLineEdit:focus { "
        "    border-color: #4CAF50; "
        "} "
        "QLineEdit:hover { "
        "    border-color: #81C784; "
        "}";
    m_nameEdit->setStyleSheet(editStyle);
    m_phoneEdit->setStyleSheet(editStyle);

    // 按钮样式
    m_submitBtn->setStyleSheet(
        "QPushButton { "
        "    background-color: #4CAF50; "
        "    color: white; "
        "    border: none; "
        "    border-radius: 6px; "
        "    font-size: 16px; "
        "    font-weight: bold; "
        "} "
        "QPushButton:hover { "
        "    background-color: #45A049; "
        "} "
        "QPushButton:pressed { "
        "    background-color: #3D8B40; "
        "} "
        "QPushButton:disabled { "
        "    background-color: #CCCCCC; "
        "    color: #666666; "
        "}"
    );

    m_clearBtn->setStyleSheet(
        "QPushButton { "
        "    background-color: #FF9800; "
        "    color: white; "
        "    border: none; "
        "    border-radius: 6px; "
        "    font-size: 16px; "
        "    font-weight: bold; "
        "} "
        "QPushButton:hover { "
        "    background-color: #F57C00; "
        "} "
        "QPushButton:pressed { "
        "    background-color: #E65100; "
        "}"
    );
}

void AddMemberPage::onSubmitClicked()
{
    if (!validateInput()) {
        return;
    }

    QString name = m_nameEdit->text().trimmed();
    QString phone = m_phoneEdit->text().trimmed();

    // 调用业务层服务添加会员
    if (m_memberService->addMember(name, phone)) {
        showSuccessMessage(QString("会员 %1 添加成功！\n手机号：%2").arg(name, phone));
        clearForm();
    } else {
        showErrorMessage("添加会员失败，请检查手机号是否已存在或稍后重试。");
    }
}

void AddMemberPage::onClearClicked()
{
    clearForm();
}

void AddMemberPage::onNameTextChanged()
{
    // 检查是否可以启用提交按钮
    bool canSubmit = !m_nameEdit->text().trimmed().isEmpty() && 
                     !m_phoneEdit->text().trimmed().isEmpty() &&
                     m_phoneEdit->hasAcceptableInput();
    m_submitBtn->setEnabled(canSubmit);
}

void AddMemberPage::onPhoneTextChanged()
{
    // 检查是否可以启用提交按钮
    bool canSubmit = !m_nameEdit->text().trimmed().isEmpty() && 
                     !m_phoneEdit->text().trimmed().isEmpty() &&
                     m_phoneEdit->hasAcceptableInput();
    m_submitBtn->setEnabled(canSubmit);
}

void AddMemberPage::clearForm()
{
    m_nameEdit->clear();
    m_phoneEdit->clear();
    m_submitBtn->setEnabled(false);
    m_nameEdit->setFocus();
}

bool AddMemberPage::validateInput()
{
    QString name = m_nameEdit->text().trimmed();
    QString phone = m_phoneEdit->text().trimmed();

    // 验证姓名
    if (name.isEmpty()) {
        showErrorMessage("请输入会员姓名！");
        m_nameEdit->setFocus();
        return false;
    }

    if (name.length() < 2) {
        showErrorMessage("会员姓名至少需要2个字符！");
        m_nameEdit->setFocus();
        return false;
    }

    // 验证手机号
    if (phone.isEmpty()) {
        showErrorMessage("请输入手机号码！");
        m_phoneEdit->setFocus();
        return false;
    }

    if (!m_phoneEdit->hasAcceptableInput()) {
        showErrorMessage("请输入正确的11位手机号码！");
        m_phoneEdit->setFocus();
        return false;
    }

    return true;
}

void AddMemberPage::showSuccessMessage(const QString &message)
{
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("添加成功");
    msgBox.setText(message);
    msgBox.setIcon(QMessageBox::Information);
    msgBox.setStyleSheet("QMessageBox { color: black; }");
    msgBox.exec();
}

void AddMemberPage::showErrorMessage(const QString &message)
{
    QMessageBox::warning(this, "输入错误", message);
}